<?php

namespace App\Http\Controllers;
use App\Models\Follow;
use App\Models\Interest;
use App\Models\Blog;
use App\Models\Reply;
use App\Models\Topic;
use App\Models\User;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;

class BlogController extends Controller
{
    //我的微博
    public function index(Request $request){
        $user_ob = User::find(Session::get('user_id'))->first();
        return view('blog.index', ['user_ob' => $user_ob]);
    }
    //微博详细
    public function info(Request $request,$id){
        $blog=Blog::find($id);
        return view('blog.info',['blog'=>$blog]);
    }
    //增加微博页面
    public function add(Request $request,$id){
        $topic=Topic::find($id);
        return view('blog.add',['topic'=>$topic]);
    }
    //增加微博
    public function doadd(Request $request){
        $user_id=$request->get('user_id');
        $topic_id=$request->get('topic_id');
        $content=$request->get('content');
        $image = $request->file('image')->store('upload/blog_img');
        $video = $request->file('video')->store('upload/blog_video');
        $topic_row=Follow::where('user_id',$user_id)->where('topic_id',$topic_id)->get();
        if($topic_row){
            $rows=Blog::create([
                'user_id'=>$user_id,
                'topic_id' =>$topic_id,
                'content'=>$content,
                'image'=>$image,
                'video'=>$video
            ]);
            if ($rows) {
                //跳转到后台的首页
                $returnJson = [
                    'code' => 200
                ];
            } else {
                $returnJson = [
                    'code' => 0,
                    'message' => '信息不完整'
                ];
            }
        }
        else{
            $returnJson = [
                'code' => 0,
                'message' => '未订阅该趣点，不能发布微博'
            ];
        }
        return response()->json($returnJson);
    }
    //发表评论
    public function doreply(Request $request){
        $blog_id=$request->get('blog_id');
        $user_id=Session::get('user_id');
        $content=$request->get('content');
        $rows=Reply::create([
            'user_id'=>$user_id,
            'blog_id' =>$blog_id,
            'content'=>$content,
        ]);
        if ($rows) {
            $blog=Blog::find($blog_id);
            $blog->subscripe_num=$blog->subscripe_num+1;
            $blog->save();
            //跳转到后台的首页
            $returnJson = [
                'code' => 200
            ];
        } else {
            $returnJson = [
                'code' => 0,
                'message' => '信息不完整'
            ];
        }
        return response()->json($returnJson);
    }
}
